package com.qth.valet.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qth.valet.common.enums.PropertyEnum;
import com.qth.valet.common.queue.DriverOrderQueueListener;
import com.qth.valet.common.queue.RedisDelayedQueue;
import com.qth.valet.common.theadlocal.UserOrDriverIdHolder;
import com.qth.valet.common.utils.StatusConstants;
import com.qth.valet.common.utils.ToolUtils;
import com.qth.valet.entity.po.DriverRecharge;
import com.qth.valet.entity.po.Property;
import com.qth.valet.entity.property.Vip;
import com.qth.valet.entity.req.RechargeReq;
import com.qth.valet.mapper.DriverRechargeMapper;
import com.qth.valet.service.DriverRechargeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qth.valet.service.PropertyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 司机充值表 服务实现类
 * </p>
 *
 * @author 蔡徐坤
 * @since 2025-09-08
 */
@Service
@RequiredArgsConstructor
public class DriverRechargeServiceImpl extends ServiceImpl<DriverRechargeMapper, DriverRecharge> implements DriverRechargeService {

    private final AlipayConfig alipayConfig;

    private final DriverRechargeMapper driverRechargeMapper;

    private final RedisDelayedQueue redisDelayedQueue;

    private final PropertyService propertyService;

    // H5支付宝标识
    private static final int PAY_CHANNEL_ZHIFUBAO_H5 = 3;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object recharge(RechargeReq req) {
        // 创建订单
        DriverRecharge driverRecharge = this.buildDriverRecharge(req);
        driverRechargeMapper.insert(driverRecharge);
        // 创建订单
        Object res = this.generateOrderInfo(driverRecharge);
        // 发送延迟消息
        redisDelayedQueue.addQueueMinutes(driverRecharge.getId(), 15, DriverOrderQueueListener.class);
        // 返回结果
        return res;
    }

    @Override
    public IPage<DriverRecharge> page(Integer driverId, long page, long size) {
        LambdaQueryWrapper<DriverRecharge> queryWrapper = new LambdaQueryWrapper<DriverRecharge>()
                .eq(DriverRecharge::getDriverId, driverId)
                .eq(DriverRecharge::getType, StatusConstants.DRIVER_RECHARGE_TYPE_COMMON) // 只查普通充值记录
                .orderByDesc(DriverRecharge::getId);
        IPage<DriverRecharge> p = new Page<>(page, size);
        return driverRechargeMapper.selectPage(p, queryWrapper);
    }

    @Override
    public Object continueRecharge(String id) {
        DriverRecharge driverRecharge = this.getById(id);
        if (driverRecharge == null) {
            throw new RuntimeException("参数异常");
        } else if (driverRecharge.getStatus() == StatusConstants.DRIVER_PAY_STATUS_CANCEL) {
            throw new RuntimeException("参数异常");
        } else if (driverRecharge.getStatus() == StatusConstants.DRIVER_PAY_STATUS_PAYED) {
            throw new RuntimeException("订单已支付，请勿重复支付");
        }
        // 此处不用发送延迟消息
        return this.generateOrderInfo(driverRecharge);
    }

    /**
     * 创建订单
     */
    private DriverRecharge buildDriverRecharge(RechargeReq req) {
        DriverRecharge driverRecharge = new DriverRecharge();
        driverRecharge.setId(ToolUtils.generateDriverOrderId());
        driverRecharge.setDriverId(UserOrDriverIdHolder.getDriverId());
        driverRecharge.setChannel(req.getPayChannel());
        driverRecharge.setStatus(StatusConstants.DRIVER_PAY_STATUS_PENDING);
        driverRecharge.setType(req.getRechargeType());
        // 普通充值：金额自定义；会员充值：金额需要查配置表
        if (req.getRechargeType() == StatusConstants.DRIVER_RECHARGE_TYPE_COMMON) {
            driverRecharge.setAmount(req.getAmount());
        } else {
            // 查会员金额
            Property vipPropertyObject = propertyService.getById(PropertyEnum.VIP.getKey());
            Vip vip = (Vip) PropertyEnum.VIP.parse(vipPropertyObject.getTheValue());
            long amt = req.getRechargeType() == StatusConstants.DRIVER_RECHARGE_TYPE_MONTH_VIP ? vip.getMonth() : vip.getYear();
            driverRecharge.setAmount(amt);
        }
        return driverRecharge;
    }

    /**
     * 创建支付订单
     */
    private Object generateOrderInfo(DriverRecharge driverRecharge) {
        // 结果
        Object res = null;
        switch (driverRecharge.getChannel()) {
            // 微信
            case StatusConstants.PAY_CHANNEL_WEIXIN:
                res = weixinPay(driverRecharge);
                throw new RuntimeException("暂不支持微信支付");
            // 支付宝
            case StatusConstants.PAY_CHANNEL_ZHIFUBAO:
                res = alipay(driverRecharge);
                break;
            // 支付宝H5支付分支
            case PAY_CHANNEL_ZHIFUBAO_H5:
                res = alipayH5(driverRecharge);
                break;
            // 银行卡
            case StatusConstants.PAY_CHANNEL_YINHANGKA:
                throw new RuntimeException("暂不支持银行卡支付");
            default:
                throw new RuntimeException("支付异常");
        }
        // 返回结果
        return res;
    }

    /**
     * 支付宝web端支付
     */
    private String alipayH5(DriverRecharge driverRecharge) {
        try {
            // H5支付宝设置订单信息
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(driverRecharge.getId());
//            model.setTotalAmount(String.valueOf(driverRecharge.getAmount() / 100.0));
            model.setTotalAmount("0.01");// 测试0.01
            model.setSubject("账户余额充值");
            model.setProductCode("QUICK_WAP_WAY");
            DateTime expireTime = DateUtil.offsetMinute(driverRecharge.getCreateTime(), 15);
            model.setTimeExpire(DateUtil.format(expireTime, "yyyy-MM-dd HH:mm:ss"));

            // H5支付宝 构造请求参数以调用接口
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            request.setBizModel(model);
            request.setNotifyUrl("https://djapi.kfcit.com/notify/alipay");// 支付结果异步通知（与App共用）
            // 设置returnUrl，支付成功后返回页面
            request.setReturnUrl("https://djweb.kfcit.com/#/");

            DefaultAlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getServerUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getPrivateKey(),
                    alipayConfig.getFormat(),
                    alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getSignType()
            );
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");

            if (response.isSuccess() && response.getBody() != null) {
                // 返回H5支付的表单HTML字符串（前端需提交该表单）
                return response.getBody();
            } else {
                throw new RuntimeException("H5订单支付失败" + response.getMsg());
            }
        } catch (AlipayApiException e){
            System.err.println("支付宝H5支付异常: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 支付宝app端支付
     */
    private String alipay(DriverRecharge driverRecharge) {
        try {
            // 1. 设置订单信息
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setOutTradeNo(driverRecharge.getId());
            model.setTotalAmount(String.valueOf((driverRecharge.getAmount() / 100)));
            model.setTotalAmount("0.01");
            model.setSubject("账户余额充值");
            DateTime expireTime = DateUtil.offsetMinute(driverRecharge.getCreateTime(), 15); // 15分钟后超时
            model.setTimeExpire(DateUtil.format(expireTime, "yyyy-MM-dd HH:mm:ss"));
            // 2. 构造请求参数以调用接口
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            request.setBizModel(model);
            request.setNotifyUrl("https://djapi.kfcit.com/notify/alipay");
            // 3. 初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            String orderStr = response.getBody();

            if (response.isSuccess()) {
                return orderStr;
            } else {
                throw new RuntimeException("支付失败");
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 微信支付
     */
    private String weixinPay(DriverRecharge driverRecharge) {
        return "";
    }

}
